package com.soboot.common.config.job.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.soboot.base.util.RetryUtil;
import com.soboot.log.utils.LogUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @Author:
 * @createTime: 2023年01月28日 20:02:07
 * @version:
 * @Description:
 * @Copyright:
 */
@Lazy
@Service
public class JobLoginService {

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.admin.username}")
    private String username;

    @Value("${xxl.job.admin.password}")
    private String password;

    private final Map<String,String> loginCookie=new HashMap<>();

    private static final String auth = "XXL_JOB_LOGIN_IDENTITY";

    public String login(){
        String url = adminAddresses+"/login";
        HttpResponse response = HttpRequest.post(url)
                .form("userName",username)
                .form("password",password)
                .execute();
        List<HttpCookie> cookies = response.getCookies();
        Optional<HttpCookie> cookieOpt = cookies.stream()
                .filter(cookie -> cookie.getName().equals(auth)).findFirst();
        if (!cookieOpt.isPresent()) {
            throw new RuntimeException("get xxl-job cookie error!");
        }

        String value = cookieOpt.get().getValue();
        loginCookie.put(auth,value);
        return value;
    }

   public String getCookie(){

        if(loginCookie.isEmpty()){
            Callable<Object> callable = new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return login();
                }
            };

            try {
                Object result = RetryUtil.retry(1, TimeUnit.SECONDS, 2, () -> callable);
                return (String) result;
            }catch (Exception ex){
                LogUtil.info("获取job的cookie出现异常:{}",ex.getMessage());
            }
        }

        return loginCookie.get(auth);
   }
}
